const {
    resolve,
    relative,
    extname,
    parse,
} = require('path')
const {
    readdirSync,
    statSync,
} = require('fs')
const webpack = require('webpack')

module.exports = {
    entry: (() => {
        const basePath = resolve(__dirname, 'src/pages')

        const entryMap = {
            'lib/vendor': ['babel-polyfill', 'whatwg-fetch'],
            'index/index': ['./src/pages/index/index.ts']
        }

        const getEntryPath = (dirPath, pathMap) => {
            const dirList = readdirSync(dirPath)
            dirList.forEach(dir => {
                switch (extname(dir)) {
                    case '':
                        getEntryPath(resolve(dirPath, dir), pathMap)
                        break;
                    case '.ts':
                        const currentPath = resolve(dirPath, dir)
                        const relativePath = `./${relative(__dirname, currentPath)}`
                        pathMap[`${relative(basePath, currentPath).replace('.ts', '')}`] = relativePath
                        break;
                }
            })
        }

        getEntryPath(basePath, entryMap)
        return entryMap
    })(),
    output: {
        path: resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    externals: [],
    devtool: 'source-map',
    context: __dirname,
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
        }),
        new webpack.optimize.CommonsChunkPlugin({
            children: true,
            deepChildren: true,
            minSize: 3,
            filename: 'lib/commons.js'
        }),
    ],
    module: {
        rules: [{
            test: /.ts$/,
            use: [{
                loader: 'babel-loader',
            }, {
                loader: 'ts-loader',
            }]
        }]
    }
}